package socket

import (
	"bufio"
	"bytes"
	"fmt"
)

func Encode(msg string) ([]byte, error) {
	var length = int32(len(msg))
	var pkg = new(bytes.Buffer)

	n, err := pkg.WriteRune(length)
	if err != nil {
		fmt.Println(n)
		return nil, err
	}
	n, err = pkg.Write([]byte(msg))

	return pkg.Bytes(), nil
}

func Decode(reader *bufio.Reader) (string, error) {
	lenBuf, _ := reader.Peek(4)
	buf := bytes.NewBuffer(lenBuf)

	length, _, _ := buf.ReadRune()
	if int32(reader.Buffered()) < length+4 {
		return "", nil
	}

	data := make([]byte, int(length+4))
	n, err := reader.Read(data)
	if err != nil {
		fmt.Println(n)
		return "", err
	}

	return string(data[4:]), nil
}
